package com.jsgt.greekfire.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import com.fhx.core.utils.NetworkUtil
import com.fhx.core.utils.NetworkUtil.getNetworkType
import com.jsgt.greekfire.event.NetChangeEvent
import org.greenrobot.eventbus.EventBus

class NetworkChangeReceiver : BroadcastReceiver() {
    private var isNetworkAvailable = false
    private var mCurNetType = 0
    private var mLastNetType = 0
    override fun onReceive(context: Context, intent: Intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info = cm.activeNetworkInfo
            if (info != null && info.isConnected) { //成功能可会回调多次
                val curNetType = getNetworkType()
                if (!isNetworkAvailable || mCurNetType != curNetType) {
                    isNetworkAvailable = true
                    mCurNetType = curNetType
                    EventBus.getDefault().post(NetChangeEvent())
                }
            } else {
                mCurNetType = NetworkUtil.NETWORK_TYPE_UNCONNECT
                if (isNetworkAvailable) {
                    isNetworkAvailable = false
                    EventBus.getDefault().post(NetChangeEvent())
                }
            }
            mLastNetType = mCurNetType
        }
    }
}